package com.atguigu.chapter08;

import com.atguigu.bean.LoginEvent;
import com.atguigu.bean.OrderEvent;
import com.atguigu.util.AnqclnUtil;
import org.apache.avro.Schema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * Author: Pepsi
 * Date: 2023/8/14
 * Desc:
 */


/*
*
* 用户恶意登录
*   这个案例对于恶意的定义是：2秒内连续登录失败就是恶意登录
*
* */


public class Flink08_Project_High_Order {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        env
                .readTextFile("input/OrderLog.csv")
                .map(line -> {
                    String[] data = line.split(",");
                    return new OrderEvent(
                            Long.valueOf(data[0]),
                            data[1],
                            data[2],
                            Long.parseLong(data[3]) * 1000
                    );
                })
                // 分配时间戳和水印 ， 因为后面要用到窗口
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((log,ts)->log.getEventTime())
                )
                // 以订单id分组
                .keyBy(OrderEvent::getOrderId)
                .window(EventTimeSessionWindows.withGap(Time.seconds(30)))
                .process(new ProcessWindowFunction<OrderEvent, String, Long, TimeWindow>() {

                    private ValueState<OrderEvent> orderEventState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        orderEventState = getRuntimeContext().getState(new ValueStateDescriptor<OrderEvent>("OrderEventState", OrderEvent.class));
                    }

                    @Override
                    public void process(Long orderId,
                                        Context context,
                                        Iterable<OrderEvent> elements,
                                        Collector<String> out) throws Exception {

                        List<OrderEvent> orderEvents = AnqclnUtil.toList(elements);

                        if (orderEvents.size() == 2) {
                            System.out.println("订单："+orderId +" 正常创建和支付...");
                        }else{

                            OrderEvent orderEvent = orderEvents.get(0);
                            if ("create".equals(orderEvent.getEventType())) {
                                // 创建的订单来了，啥也说名不了，只能把这个订单对象更新到状态中
                                orderEventState.update(orderEvent);
                            }else{

                                // 注意：pay来了分为两种情况：
                                //              1. 前面没有create   -》 系统错误
                                //              2. 有create    但是 pay 30分钟后 才支付的，不在一个窗口    -> 订单超时支付...系统有bug

                                if (orderEventState.value() == null) {
                                    // 这种情况就是 pay来了，要判断前面有没有支付，没有支付
                                    out.collect("订单："+orderId+" 只有pay，没有create，请检查系统是否有bug...");
                                }else{
                                    // pay来了，状态里面有create，
                                    out.collect("订单："+orderId+" 超时支付，请检查系统是否有bug...");
                                }
                            }

                        }
                    }
                })
                .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
